﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using RapidAddition.FIXDataDictionary;
using RapidAddition.FIXEngine;

namespace LiquidTrading.RapidAdditionHelper.Clients
{
    public class FIXServer : RapidAddition.FIXEngine.IFIXSessionCallback
    {
        /// <summary>
        /// Use file based FIX dictionary repository, with a file logger
        /// </summary>
        /// <param name="creds"></param>
        public FIXServer(Credentials.FileRepoFileLog creds)
        {
            DataDictionary = new CFIXDataDictionary(creds.RepoLocation, creds.FIXVersion);

            Counterparty = new CFIXParty(creds.FIXSenderId, creds.FIXSenderId, "", 0);
            Listener = new CFIXParty(creds.FIXTargetId, creds.FIXTargetId, creds.FIXHost, creds.FIXPort);

            Conversation = new CFIXConversation(Listener, Counterparty, creds.FIXVersion, false, 120, false);
            Conversation.ConnectRetryInterval = 10;

            MessageStore = new CFIXMessageStore(creds.LogLocation, Conversation, creds.LogAllMessages);
        }

        public const string FIXVERSION42 = "FIX.4.2";
        public const int TAG_EXDESTINATION = 100;
        public const int TAG_9882 = 9882;

        public CFIXDataDictionary DataDictionary { get; protected set; }
        public CFIXParty Listener { get; protected set; }
        public CFIXParty Counterparty { get; protected set; }
        public CFIXConversation Conversation { get; protected set; }
        public IFIXMessageStore MessageStore { get; protected set; }
        public CFIXSession Session { get; protected set; }


        public bool IsLoggedOut { get { return Session != null ? Session.State == EFIXSessionState.LoggedOut : false; } }


        public virtual void Start(bool resetSequenceNum)
        {
            Session = new CFIXSession(Conversation, DataDictionary, MessageStore, this, null);
            Session.SessionCallback = this; 
            Session.Listen(resetSequenceNum);                 
        }


        #region IFIXSessionCallback Members

        public virtual void NewState(CFIXSession Session, EFIXSessionState State)
        {
            Console.WriteLine("NewState: " + State.ToString());
        }

        public virtual void ReceiveMessage(CFIXSession Session, CFIXMessage Message, int SessionID, int ID, bool DoNotProcess)
        {
            Console.WriteLine("ReceiveMessage: " + SessionID + " " + ID + " " + Message.GetType().Name);
        }

        public virtual void SendMessage(CFIXSession Session, CFIXMessage Message)
        {
            Console.WriteLine("SendMessage: " + Message.GetType().Name);
        }

        #endregion



    }
}
